package kdxf

import (
	"bytes"
	"encoding/binary"
	log "github.com/astaxie/beego/logs"
	"net"
)

var headFrame uint32 = 0xaa55eeaa

type kdxf_head struct {
	framHead    int32 /* 帧头*/
	sessionId   int32
	fileType    int32
	fileNameLen int32
	textLen     int32
	pitch       int32
	volume      int32
	speed       int32
	text        string
	fileName    string
}

func protoEnCodeHead(head kdxf_head) *bytes.Buffer {

	buf := new(bytes.Buffer)

	binary.Write(buf, binary.BigEndian, headFrame)
	binary.Write(buf, binary.BigEndian, head.sessionId)
	binary.Write(buf, binary.BigEndian, int32(3))
	binary.Write(buf, binary.BigEndian, int32(len(head.fileName)))
	binary.Write(buf, binary.BigEndian, int32(len(head.text)))
	binary.Write(buf, binary.BigEndian, head.pitch)
	binary.Write(buf, binary.BigEndian, head.speed)
	binary.Write(buf, binary.BigEndian, head.volume)
	binary.Write(buf, binary.BigEndian, []byte(head.fileName))
	binary.Write(buf, binary.BigEndian, []byte(head.text))

	return buf
}

type kexf_result struct {
	sessionId int32
	result    int32
}

func protoDecodeInt(serv net.Conn) (int32, error) {

	var num int32
	buffer := make([]byte, 4)

	recved := 0
	for recved < 4 {
		recvlen, err := serv.Read(buffer[recved:])
		if err != nil {
			log.Error("recv failed.", err)
			return 0, err
		}

		recved += recvlen
	}

	buf := bytes.NewReader(buffer)
	err := binary.Read(buf, binary.BigEndian, &num)

	return num, err
}

func protoDecodeResult(ttsClient net.Conn) (result kexf_result, err error) {

	result.sessionId, err = protoDecodeInt(ttsClient)
	if err != nil {
		log.Error("recv from tts client failed:%v", err)
		return
	}

	result.result, err = protoDecodeInt(ttsClient)
	if err != nil {
		log.Error("recv from tts client failed:%v", err)
		return
	}

	return
}
